var http = require('https')
var fs = require("fs");
var path = require("path");
var template = require('art-template'); //http://aui.github.io/art-template/zh-cn/docs/index.html
var rule = template.defaults.rules[1];
//更改模板解析规则，防止与vue的{{}}冲突
rule.test = new RegExp(rule.test.source.replace('{{', '{{{').replace('}}', '}}}'));
template.defaults.minimize = true; // 压缩代码
template.defaults.htmlMinifierOptions = {
    collapseWhitespace:true,
    minifyCSS: true,  
    minifyJS: true,
    // 运行时自动合并：rules.map(rule => rule.test)
    ignoreCustomFragments: []
}; 
var schemaCfgs = {
	common: {
		dir: 'admin',
		theme: "bg-gradual-blue",
		fieldOrders:{"name":1,"order":1000,"open":2000} ,//字段排序
		addExcludes:["sys","passed"]//excludes排除那些
	},
	schemas: {
		//Area: {"title":"区域",addExcludes:["common","level"]},//excludes排除那些
		//Building:{"title":"楼栋"},
		//Dormitory:{"title":"宿舍"} 
		//Equipment:{"title":"设备"}
		//DormitoryEquipment:{"title":"设备分配"}
		//Repair:{"title":"维修记录"}
		//College:{"title":"学院"}
		//Major:{"title":"专业"},
		//Grade:{"title":"年级"},
		//Classs:{"title":"班级"},
		User:{"title":"用户"},
	}
}

gen(schemaCfgs)

function gen(schemaCfgs) {
	http.get('https://haolaoshiya.com/dms/swagger/v1/swagger.json', (res) => {
		const {
			statusCode
		} = res;
		const contentType = res.headers['content-type'];
		let error;
		if (statusCode !== 200) {
			error = new Error(`请求失败。状态码: ${statusCode}`);
		} else if (!/^application\/json/.test(contentType)) {
			error = new Error(`无效的 content-type.期望 application/json 但获取的是 ${contentType}`);
		}
		if (error) {
			console.error(error.message);
			// 消耗响应数据以释放内存
			res.resume();
			return;
		}

		res.setEncoding('utf8');
		let rawData = '';
		res.on('data', (chunk) => {
			rawData += chunk;
		});
		res.on('end', () => {
			try {
				const parsedData = JSON.parse(rawData);
				var schemas = parsedData.components.schemas
				for (let k in schemaCfgs.schemas) { //循环生成配置
					var s = schemas[k]
					var cfg = schemaCfgs.schemas[k]
					gencode(k.toLowerCase(), s, cfg, schemaCfgs.common)
				}
				//console.log(schemas);
			} catch (e) {
				console.error(e.message);
			}
		});
	}).on('error', (e) => {
		console.error(`错误: ${e.message}`);
	});
}
//recursive: true 参数，不管创建的目录 /tmp 和 /tmp/a 是否存在：
function gencode(schemaName, schemaObj, schemaCfg, commonCfg) {
	//创建目录
	var dirName=(commonCfg.dir ? commonCfg.dir : "") 
	var dir = path.resolve(__dirname, "../pages/" + dirName+ "/" + schemaName + "/")
	dir = dir + "/"
	fs.mkdir(dir, {
		recursive: true
	}, (err) => {
		if (err) throw err;
		var cfg = Object.assign({
			name: schemaName
		}, commonCfg)
		
		//读pages.json文件
		var pagesjsonfile=path.resolve(__dirname, "../" )+'/pages.json'
		var    rawdata = fs.readFileSync(pagesjsonfile);
		let pagesjson = JSON.parse(rawdata);
		
		//生成list页面
		var listHtml = template(__dirname + '/list_tpl.vue', cfg);
		var filename = 'list'
		var ext = ".vue"
		var filepath = dir + filename + ext
		if (fs.existsSync(filepath)) {
			//获取文件名(不包含后缀) 第二个参数即要删除的后缀
			//console.log(path.basename(filename, '.vue'));
			filepath = filepath = dir + filename + "_gen" + ext
		}
		fs.writeFile(filepath, listHtml, function(err) {
			if (err) {
				return console.error(err);
			}
		});
		//添加到pages.json
		var listpath=`pages/${dirName}/${schemaName}/list`
		if(!pagesjson.pages.some(ele => ele.path === listpath) ){
			pagesjson.pages.push({"path":listpath })
		}
		
		
		//生成add页面
		var obj=parseAddObj(schemaName, schemaObj, schemaCfg, commonCfg) 
		cfg.obj=obj;
		var addHtml = template(__dirname + '/add_tpl.vue', cfg);
		filename = 'add'
		var filepath = dir + filename + ext
		if (fs.existsSync(filepath)) {
			//获取文件名(不包含后缀) 第二个参数即要删除的后缀
			//console.log(path.basename(filename, '.vue'));
			filepath = filepath = dir + filename + "_gen" + ext
		}
		fs.writeFile(filepath,addHtml, function(err) {
			if (err) {
				return console.error(err);
			}
		});
		//添加到pages.json
		var addpath=`pages/${dirName}/${schemaName}/add`
		if(!pagesjson.pages.some(ele => ele.path === addpath) ){
			pagesjson.pages.push({"path":addpath })
		}

		let jsonstr = JSON.stringify(pagesjson);
		fs.writeFileSync(pagesjsonfile, jsonstr);
		
		//更改pages.js文件
		//读pages.js文件
		var pagesjsfile=path.resolve(__dirname, "../store/module/" )+'/pages.js'
		rawdata = fs.readFileSync(pagesjsfile);
		eval(rawdata.toString().replace("export default","var pagesjsobj="))
		var d=pagesjsobj.state
		if(dirName){
			d=pagesjsobj.state[dirName]
		}
		d[schemaName]={
			list: {
				text: `${schemaCfg.title}管理`,
				path: `/pages/${dirName}/${schemaName}/list`,
				url: `/api/${dirName}/${schemaName}/List`
			},
			add: {
				text: `${schemaCfg.title}添加`,
				path: `/pages/${dirName}/${schemaName}/add`,
				url: `/api/${dirName}/${schemaName}/add`
			},
			delete: {
				text: `${schemaCfg.title}删除`,
				url: `/api/${dirName}/${schemaName}/delete`
			},
			detail: {
				text: `${schemaCfg.title}详情`,
				path: `/pages/${dirName}/${schemaName}/detail`,
				url: `/api/${dirName}/${schemaName}/get`
			},
			update: {
				text: `${schemaCfg.title}修改`,
				url: `/api/${dirName}/${schemaName}/update`
			}
		}
		//console.log(JSON.stringify(pagesjsobj)) 
		fs.writeFileSync(pagesjsfile, "export default "+JSON.stringify(pagesjsobj));       			   
	});

}

function parseAddObj(schemaName, schemaObj, schemaCfg, commonCfg) {
	var ret={required:{},properties:{}}
	ret.required=schemaObj.required
    fields=[]
	var excludes=commonCfg.addExcludes
	excludes=excludes.concat(schemaCfg.addExcludes?schemaCfg.addExcludes:[])
	for(let k in  schemaObj.properties){
		var v = schemaObj.properties[k] 
		if(!v.readOnly && !(excludes.includes(k)) && !v["$ref"]){//排除一些
		    var title=k
			if(v.description){
				title=v.description.split(/[,.。，;；]/)[0]
			}
		  
		    v.title= title.substr(0,4)
			v.order=commonCfg.fieldOrders[k]?commonCfg.fieldOrders[k]:200
			v.name=k
			//判断字段类型type，如果字段名是pic则是图片类型，如果以Id结尾，则是数据选择框类型
			if(k=="pic"){
				v.type="image"
			}else if(k.endsWith("Id")){
				v.type="datapicker"
				o=schemaObj.properties[k.replace("Id","")]
				//console.log(o)
				if(o){
					ovarray=o["$ref"].split("/")
					v.classname=ovarray[ovarray.length-1].toLowerCase()
				}else if(k=="parentId"){
					v.classname=schemaName
				}else{
					v.classname=k.replace("Id","")
				}
				
			}
			else if(k=="intro"||k=="content"||k=="detail"){
				v.type="textarea"
			}else if(v.format){//根据format判断类型
				switch(v.format){
					case "date-time":
					  v.type="datetime"
					  break
				}
			}else if(k=="tel"||k=="telephone"||k=="mobile"){//判断电话类型		
					  v.type="tel"
			}
		    fields.push(v)
			//console.log(v.order)
		}											    
	}
	fields=fields.sort(function(f1,f2){
		return f1.order-f2.order
	})
	for(let idx in  fields){
		var f=fields[idx]
		ret.properties[f.name]=f								    
	}
	return ret
}
/*
			fs.readFile(dir+'index.vue', function(err, data) {
				if (err) {
					return console.error(err);
				}
				console.log("异步读取文件数据: " + data.toString());
			});
			*/
